package com.tarena.lbs.coupon.rpc;

import com.tarena.lbs.activity.api.ActivityApi;
import com.tarena.lbs.activity.api.pojo.ActivityDto;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.utils.SnowflakeIdGenerator;
import com.tarena.lbs.coupon.api.CouponApi;
import com.tarena.lbs.coupon.api.pojo.param.UserCouponsParam;
import com.tarena.lbs.coupon.dao.mapper.CouponMapper;
import com.tarena.lbs.coupon.dao.mapper.StockMapper;
import com.tarena.lbs.coupon.dao.mapper.UserCouponsMapper;
import com.tarena.lbs.coupon.pojo.po.CouponPO;
import com.tarena.lbs.coupon.pojo.po.UserCouponsPO;
import com.tarena.lbs.coupon.pojo.vo.UserCouponsVO;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author: goodman
 * @Date: 2025/5/15 17:31
 */

@Slf4j
@Component
@DubboService
public class CouponApiImpl implements CouponApi {
    @DubboReference
    private ActivityApi activityApi;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private UserCouponsMapper userCouponsMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private SnowflakeIdGenerator idGenerator;
    @Override
    public void receiveCoupon(UserCouponsParam param) throws BusinessException {
        //获取用户信息 param是前端传来的 adminDto是后端保存的token 判断是否一致
        AdminDto adminDto = userApi.getAdminById(param.getUserId());
        if (adminDto.getId()!=param.getUserId()){
            throw new RuntimeException("当前用户和登录用户不一致");
        }
        //活动是否存在
        Boolean result=activityApi.activityVisible(param.getUserId(),param.getActivityId());
        //参与活动时间在有效期吗
        ActivityDto activityDto=activityApi.getActivityById(param.getActivityId());
        Date now=new Date();
        if(now.before(activityDto.getEndDate())){
            throw new RuntimeException("不在活动时间内");
        }
        if(activityDto.getStatus()!=1){
            throw new RuntimeException("活动未开始始或结束");
        }
        if(activityDto.getTargetCustomer()==null){
            throw new RuntimeException("目标活动人群为空");
        }
        Integer businessId=userApi.getBusinessId(param.getUserId());
        //检查用户所属人群
        List<Integer> list=userApi.getUserGroupIds(param.getUserId(),businessId);
        //活动的活动人群，是String
        String targetCustomer=activityDto.getTargetCustomer();
        boolean isTarget=false;
        //遍历List version2使用while判断String的,是否存在进行分割
        for(Integer number:list){
            //查看当前List的元素在这个String里存在吗，因为String里是,分割
            boolean contains = targetCustomer.contains(number+"");
            if (contains==true){
                isTarget=true;
                UserCouponsPO userCouponsPO=new UserCouponsPO();
                BeanUtils.copyProperties(userCouponsPO,param);
                return;
            }else{
                throw new RuntimeException("用户不是活动的目标人群");
            }
        }
        //用户是活动目标人群
        //检查优惠券
        CouponPO couponPO =couponMapper.selectById(param.getCouponId());
        if (couponPO==null){
            throw new RuntimeException("活动券不存在");
        }
        //检查优惠券状态0未使用1已使用2已过期3已锁定
        if (couponPO.getStatus()!=0){
            throw new RuntimeException("优惠券不可使用，已使用,已过期或已锁定");
        }
        //优惠券的最大领取上线
        int userGet=couponPO.getUsageLimit();
        //从数据库查询优惠券id使用COUNT（*）来和最大上限比较
        int userCouponCount=userCouponsMapper.selectCountById(param.getCouponId(),param.getUserId());
        if (userCouponCount>userGet){
            throw new RuntimeException("用户领取优惠券达到上线");
        }
        //查询优惠券库存
        int stockNum=stockMapper.selectNumById(param.getCouponId());
        if(stockNum==0){
            throw new RuntimeException("优惠券库存为0");
        }
        //生成优惠券编码
        String billId=generateBillId();
        //设置param的couponcode
        param.setCouponCode(billId);
        //记录用户领取记录,响usercoupon表里新增一条couponid和userid的数据，这样可以给上面查询上线使用
        UserCouponsPO userCouponsPO=new UserCouponsPO();
        BeanUtils.copyProperties(param,userCouponsPO);
        userCouponsPO.setUpdateAt(new Date());
        userCouponsPO.setCreateAt(new Date());
        userCouponsMapper.insert(userCouponsPO);
        //扣减库存
        int newNum=stockNum-1;
        stockMapper.couponMinusOne(newNum);
    }
    private String generateBillId() {
        return idGenerator.nextId()+"";
    }
}
